import sys

import PySide6
from PySide6.QtCore import Signal
from PySide6.QtGui import QColor, QIcon
from PySide6.QtWidgets import QWidget, QHBoxLayout, QPushButton, QApplication, QVBoxLayout, \
    QMessageBox

from extend_ui.err_log import log_decorator
from extend_ui.table_class import Table_E2prom
import resources.resources_rc  # 导入图片资源不可去


class E2prom_Manage(QWidget):
    signal_button_alone_save = Signal(int)

    def __init__(self, parent=None, config=None):
        super(E2prom_Manage, self).__init__()
        # 获取变量
        self.config = config
        self.signal_operat = parent.signal_operat
        self.signal_table_info = parent.signal_table_info
        self.table_info = parent.table_info
        self.queue_logging = parent.queue_logging

        # 创建变量
        self.e2prom_count = self.table_info['isEEPROM'].count(1)    # 获取e2prom变量个数

        self.initLayout()
        # self.add_table_data()
        self.show()


    def initLayout(self):
        """ 创建视图 """
        # 初始化窗口
        self.icon_logo = QIcon(':/logo.ico')
        self.setWindowIcon(self.icon_logo)
        self.setWindowTitle('EEPROM变量')
        self.setMinimumHeight(567)
        self.setMinimumWidth(600)
        self.layout = QVBoxLayout(self)
        self.button_layout = QHBoxLayout()

        # 创建table
        self.table_widget2 = Table_E2prom(self,
                                          signal_table_info=self.signal_table_info,
                                          table_info=self.table_info,
                                          signal_button_alone_save=self.signal_button_alone_save)
        self.signal_button_alone_save.connect(self.button_alone_save_slot)
        # self.table_widget = QTableWidget()
        # self.table_widget.verticalHeader().setVisible(False)
        # self.table_widget.setColumnWidth(0, 70)
        # self.table_widget.setColumnCount(7)  # 设置列数
        # self.table_widget.verticalHeader().setVisible(False)  # 设置表头状态
        # self.table_widget.setHorizontalHeaderLabels(['参数地址', '类型号', '参数名称', '当前值（单位）', '缺省值', '类型', '保存到E2PROM'])  # 设置列名
        # self.table_widget.setEditTriggers(QAbstractItemView.NoEditTriggers)  # 禁止编辑
        # self.table_widget.setSelectionBehavior(QAbstractItemView.SelectItems)  # 设置选择行为为单行
        # self.table_widget.cellDoubleClicked.connect(self.double_clicked_slot)
        self.layout.addWidget(self.table_widget2)

        # 创建button
        self.button_load = QPushButton('从配置文件加载缺省值')  # 将缺省值加载到RAM
        self.button_load.setToolTip('将缺省值加载到RAM中')
        self.button_load.clicked.connect(self.button_load_slot)
        self.button_default = QPushButton('从E2PROM读取值')  # 将ROM的值加载到RAM
        self.button_default.setToolTip('将ROM的值加载到RAM')
        self.button_default.clicked.connect(self.button_default_slot)
        self.button_save = QPushButton('将值保存到配置文件的缺省值')  # 将RAM的值保存到csv
        self.button_save.setToolTip('将RAM的值保存到配置文件')
        self.button_save.clicked.connect(self.button_save_slot)
        self.button_solid = QPushButton('将值写入E2PROM')  # 将RAM的值固化到ROM
        self.button_solid.setToolTip('将RAM的值固化到ROM')
        self.button_solid.clicked.connect(self.button_solid_slot)

        self.button_layout.addWidget(self.button_load)
        self.button_layout.addWidget(self.button_default)
        self.button_layout.addWidget(self.button_save)
        self.button_layout.addWidget(self.button_solid)
        self.layout.addLayout(self.button_layout)

    # def add_table_data(self):
    #     """ 向表中添加数据 """
    #     self.para_addr = []  # 参数地址
    #     para_tyn = []  # 类型号
    #     para_name = []  # 参数名
    #     curr_value = []  # 当前值
    #     para_def = []  # 缺省值
    #     RW_type = []  # 读写类型
    #     buttons = []    # 保存按钮
    #
    #     for i in range(len(self.table_info['isEEPROM'])):
    #         if self.table_info['isEEPROM'][i] == 1:
    #             self.para_addr.append(str(self.table_info['addr'][i]))
    #             para_tyn.append(self.table_info['type_lv2'][i])
    #             para_name.append(self.table_info['var_comment'][i])
    #             if self.table_info['var_current'][i] == '':
    #                 if self.table_info['var_type'][i] in ['3', 'enum']:
    #                     if not self.table_info['action_define']:
    #                         curr_value.append(str(0))
    #                     else:
    #                         curr_value.append(list(self.table_info['action_define'][i].values())[0])
    #                 elif self.table_info['var_type'][i] in ['5', 'bit']:
    #                     curr_value.append('0x0')
    #                 elif self.table_info['var_type'][i] in ['1', 'int']:
    #                     curr_value.append(str(0) + self.table_info['var_unit'][i])
    #                 else:
    #                     curr_value.append(str(0.0) + self.table_info['var_unit'][i])
    #             else:
    #                 if self.table_info['var_type'][i] in ['3', 'enum']:
    #                     if not self.table_info['action_define']:
    #                         curr_value.append(str(0))
    #                     else:
    #                         curr_value.append(
    #                             self.table_info['action_define'][i][str(self.table_info['var_current'][i])])
    #                 elif self.table_info['var_type'][i] in ['5', 'bit']:
    #                     if not self.table_info['action_define'][i]:
    #                         curr_value.append('0x0')
    #                     else:
    #                         curr_value.append(hex(int(self.table_info['var_current'][i])))
    #                 elif self.table_info['var_type'][i] in ['1', 'int']:
    #                     if self.table_info['var_unit'][i]:
    #                         curr_value.append(str(int(self.table_info['var_current'][i])) + self.table_info['var_unit'][i])
    #                     else:
    #                         curr_value.append(str(int(self.table_info['var_current'][i])))
    #                 else:
    #                     if self.table_info['var_unit'][i]:
    #                         curr_value.append(str(self.table_info['var_current'][i]) + self.table_info['var_unit'][i])
    #                     else:
    #                         curr_value.append(str(self.table_info['var_current'][i]))
    #             if self.table_info['var_default'][i]:
    #                 if self.table_info['var_type'][i] in ['3', 'enum']:
    #                     if not self.table_info['action_define'][i]:
    #                         para_def.append(str(self.table_info['var_default'][i]))
    #                     else:
    #                         para_def.append(
    #                             self.table_info['action_define'][i][self.table_info['var_default'][i]])
    #                 elif self.table_info['var_type'][i] in ['5', 'bit']:
    #                     para_def.append(hex(int(float(self.table_info['var_default'[i]]))))
    #                     # if not self.table_info['action_define'][i]:
    #                     #     para_def.append(hex(int(float(self.table_info['var_default'[i]]))))
    #                     # else:
    #                     #     if int(float(self.table_info['var_default'][i])) == 0:
    #                     #         para_def.append('0x0')
    #                     #     else:
    #                     #         para_def.append(self.table_info['action_define'][i][
    #                     #                             int(math.log(int(float(self.table_info['var_default'][i])), 2))])
    #                 else:
    #                     # para_def.append(str(self.table_info['var_default'][i]))
    #                     if 0.0 < abs(self.table_info['var_default'][i]) < 0.01:
    #                         para_def.append('{:.2e}'.format(self.table_info['var_default'][i]))
    #                     elif self.table_info['var_default'][i] > 100000:
    #                         para_def.append('{:.4e}'.format(self.table_info['var_default'][i]))
    #                     else:
    #                         if self.table_info['var_decimal'][i]:
    #                             para_def.append(
    #                                 ('%.' + str(self.table_info['var_decimal'][i]) + 'f' % self.table_info['var_default'][i]) + self.table_info['var_unit'][i])
    #                         else:
    #                             para_def.append(
    #                                 ('%.2f' % self.table_info['var_default'][i]) + self.table_info['var_unit'][i])
    #             else:
    #                 if self.table_info['var_type'][i] in ['3', 'enum']:
    #                     if not self.table_info['action_define'][i]:
    #                         para_def.append('0')
    #                     else:
    #                         para_def.append(list(self.table_info['action_define'][i].values())[0])
    #                 elif self.table_info['var_type'][i] in ['5', 'bit']:
    #                     if not self.table_info['action_define'][i]:
    #                         para_def.append('0x0')
    #                     else:
    #                         para_def.append('0x0')
    #                 else:
    #                     para_def.append('0.0')
    #             if self.table_info['isWritable'][i] == 1:
    #                 RW_type.append('R/W')
    #             else:
    #                 RW_type.append('Ro')
    #             # print(curr_value)
    #             # print(para_def)
    #             button = QPushButton('保存')
    #             button.clicked.connect(partial(self.button_alone_save_slot, para_adr=self.table_info['addr'][i]))
    #             buttons.append(button)
    #         else:
    #             pass
    #
    #     self.table_widget.setRowCount(len(self.para_addr))  # 设置行数
    #     # 将数据添加到表格当中
    #     for i in range(len(self.para_addr)):
    #         tableitem1 = QTableWidgetItem(self.para_addr[i])
    #         tableitem1.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
    #         tableitem2 = QTableWidgetItem(para_tyn[i])
    #         tableitem2.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
    #         tableitem3 = QTableWidgetItem(para_name[i])
    #         tableitem3.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
    #         tableitem4 = QTableWidgetItem(curr_value[i])
    #         tableitem4.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
    #         tableitem5 = QTableWidgetItem(para_def[i])
    #         tableitem5.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
    #         tableitem6 = QTableWidgetItem(RW_type[i])
    #         tableitem6.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
    #         self.table_widget.setItem(i, 0, tableitem1)
    #         self.table_widget.setItem(i, 1, tableitem2)
    #         self.table_widget.setItem(i, 2, tableitem3)
    #         self.table_widget.setItem(i, 3, tableitem4)
    #         self.table_widget.setItem(i, 4, tableitem5)
    #         self.table_widget.setItem(i, 5, tableitem6)
    #         self.table_widget.setCellWidget(i, 6, buttons[i])
    #     # 给背景区分颜色
    #     type_name_list = list(set(para_tyn))
    #     for i in range(self.table_widget.rowCount()):
    #         if type_name_list.index(self.table_widget.item(i, 1).text()) % 2 == 0:
    #             self.setRowColor(i, QColor(240, 240, 240, 255))     # 灰色
    #         else:
    #             pass
    #
    # def setRowColor(self, row, color):
    #     """ 为每一行的item 设置颜色， -1 是不包括按钮 """
    #     for col in range(self.table_widget.columnCount()-1):
    #         item = self.table_widget.item(row, col)
    #         item.setBackground(color)


    # def double_clicked_slot(self, row, col):
    #     if col == 3:
    #         para_addr = int(self.table_widget.item(row, 0).text())
    #         if self.table_info['var_type'][para_addr] in ['5', 'bit'] and self.table_info['action_define'][para_addr]:
    #             dialog_table = Dialog_Table(self)
    #             dialog_table.display(para_addr)
    #         elif self.table_info['var_type'][para_addr] in ['3', 'enum'] and self.table_info['action_define'][
    #             para_addr]:
    #             dialog_combox = Dialog_Combox(self)
    #             dialog_combox.display(para_addr)
    #         else:
    #             dialog_edit = Dialog_Edit(self)
    #             dialog_edit.display(para_addr)

    def refresh(self, addrs, values):
        self.table_widget2.refresh()
        # if self.isVisible():
        #     for i in range(len(addrs)):
        #         if str(addrs[i]) in self.para_addr:
        #             if self.table_info['var_type'][addrs[i]] in ['bit', '5']:
        #                 self.table_widget.item(self.para_addr.index(str(addrs[i])), 3).setText(hex(values[i]))
        #             elif self.table_info['var_type'][addrs[i]] in ['enum', '3']:
        #                 self.table_widget.item(self.para_addr.index(str(addrs[i])), 3).setText(
        #                     self.table_info['action_define'][addrs[i]][str(values[i])])
        #             elif self.table_info['var_type'][addrs[i]] in ['int', '1']:
        #                 self.table_widget.item(self.para_addr.index(str(addrs[i])), 3).setText(
        #                     str(values[i]) + self.table_info['var_unit'][addrs[i]])
        #             else:
        #                 if 0.0 < abs(values[i]) < 0.01:
        #                     self.table_widget.item(self.para_addr.index(str(addrs[i])), 3).setText(
        #                         '{:.2e}'.format(values[i]) + self.table_info['var_unit'][addrs[i]])
        #                 elif values[i] > 100000:
        #                     self.table_widget.item(self.para_addr.index(str(addrs[i])), 3).setText(
        #                         '{:.4e}'.format(values[i]) + self.table_info['var_unit'][addrs[i]])
        #                 else:
        #                     if self.table_info['var_decimal'][addrs[i]]:
        #                         self.table_widget.item(self.para_addr.index(str(addrs[i])), 3).setText(
        #                             ('%.' + self.table_info['var_decimal'][addrs[i]] + 'f' % values[i]) + self.table_info['var_unit'][
        #                                 addrs[i]])
        #                     else:
        #                         self.table_widget.item(self.para_addr.index(str(addrs[i])), 3).setText(
        #                             ('%.2f' % values[i]) + self.table_info['var_unit'][addrs[i]])


    def button_alone_save_slot(self, para_adr):
        """ 每个单独的按钮响应的动作 """
        self.dis_btn()
        replay = QMessageBox.question(self, '提示', '是否要保存', QMessageBox.Yes | QMessageBox.No)
        if replay == QMessageBox.Yes:
            self.signal_operat.emit(3, 1, [2, para_adr, 1])
        else:
            pass

    @log_decorator
    def button_load_slot(self):
        """ 将数据从配置文件的默认值加载到当前值 """
        self.dis_btn()
        reply = QMessageBox.question(self,
                                     "提示",
                                     "是否确认加载？",
                                     QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            var_addr_list = []
            var_value_list = []
            for i in range(len(self.table_info['var_current'])):
                if self.table_info['isEEPROM'][i] == 1 and self.table_info['isWritable'][i] == 1:
                    var_addr_list.append(self.table_info['addr'][i])
                    if self.table_info['var_default'][i]:
                        if self.table_info['var_type'][i] in ['5', 'bit', '3', 'enum', '1', 'int']:
                            var_value_list.append(int(self.table_info['var_default'][i]))
                        else:
                            var_value_list.append(float(self.table_info['var_default'][i]))
                    else:
                        if self.table_info['var_type'][i] in ['5', 'bit', '3', 'enum', '1', 'int']:
                            var_value_list.append(int(0))
                        else:
                            var_value_list.append(float(0.0))

            for i in range(len(var_addr_list) - 1):
                if var_addr_list[i] != var_addr_list[i+1] - 1:
                    # my_logger.warning('加载缺省值时出现不连续的地址:' + str(var_addr_list))
                    self.queue_logging.put([1, 2, '加载缺省值时出现不连续的地址:' + str(var_addr_list)])
                    QMessageBox.information(self, '提示', '加载缺省值出现错误\n请查看日志', QMessageBox.Yes)
                    return
            # print(var_addr_list, var_value_list)
            self.signal_table_info.emit(1, var_addr_list, var_value_list)
            self.response('加载成功!')
        else:
            pass
        self.en_btn()

    @log_decorator
    def button_default_slot(self):
        """ 将e2prom的值加载到 当前值 """
        self.dis_btn()
        reply = QMessageBox.question(self,
                                     "提示",
                                     "是否从ROM读取数据？",
                                     QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.signal_operat.emit(3, 1, [1, 0, self.e2prom_count])
        else:
            self.en_btn()

    @log_decorator
    def button_save_slot(self):
        """ 将当前文件加载到缺省值 """
        self.dis_btn()
        reply = QMessageBox.question(self,
                                     "提示",
                                     "是否保存到配置文件？",
                                     QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.signal_operat.emit(3, 2, [None])
        else:
            pass
        self.en_btn()

    @log_decorator
    def button_solid_slot(self):
        """ 将当前值写入 E2prom """
        self.dis_btn()
        reply = QMessageBox.question(self,
                                     "提示",
                                     "是否将数据固化到ROM？",
                                     QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.signal_operat.emit(3, 1, [2, 0, self.e2prom_count])
        else:
            self.en_btn()

    def response(self, MSG):
        """ 主窗口的响应 """
        QMessageBox.information(self, '提示', MSG, QMessageBox.Yes)
        self.en_btn()

    def update_default_one(self, addr):
        self.table_widget2.update_default_one(addr)

    def update_default(self):
        """ 保存缺省值成功后 更新表中数据 """
        self.table_widget2.update_default()
        # for i in range(len(self.table_info['var_current'])):
        #     self.table_info['var_default'][i] = str(self.table_info['var_current'][i])
        # for i in range(self.table_widget.rowCount()):
        #     if self.table_info['var_type'][i] in ['5', 'bit']:
        #         if not self.table_info['action_define'][i]:
        #             self.table_widget.item(i, 4).setText(str(hex(int(float(self.table_info['var_current'][i])))))
        #         elif self.table_info['var_current'][i] == 0:
        #             self.table_widget.item(i, 4).setText('0x0')
        #         else:
        #             self.table_widget.item(i, 4).setText(self.table_info['action_define'][i][
        #                                                     int(math.log(int(self.table_info['var_current'][i]), 2))])
        #     elif self.table_info['var_type'][i] in ['3', 'enum']:
        #         if not self.table_info['action_define'][i]:
        #             self.table_widget.item(i, 4).setText(str(self.table_info['var_current'][i]))
        #         else:
        #             self.table_widget.item(i, 4).setText(
        #                 self.table_info['action_define'][i][int(self.table_info['var_current'][i])])
        #     else:
        #         # self.table_widget.item(i, 4).setText(str(self.table_info['var_current'][i]))
        #
        #         if 0.0 < abs(self.table_info['var_current'][i]) < 0.01:
        #             self.table_widget.item(i, 4).setText('{:.2e}'.format(self.table_info['var_current'][i]))
        #         elif self.table_info['var_current'][i] > 100000:
        #             self.table_widget.item(i, 4).setText('{:.4e}'.format(self.table_info['var_current'][i]))
        #         else:
        #             if self.table_info['var_decimal'][i]:
        #                 self.table_widget.item(i, 4).setText(
        #                     ('%.' + self.table_info['var_decimal'][i] + 'f' % self.table_info['var_current'][i]))
        #             else:
        #                 self.table_widget.item(i, 4).setText(
        #                     ('%.2f' % self.table_info['var_current'][i]) + self.table_info['var_unit'][i])

    def dis_btn(self):
        """ 触发事件禁用全局按钮 """
        self.button_load.setEnabled(False)
        self.button_default.setEnabled(False)
        self.button_save.setEnabled(False)
        self.button_solid.setEnabled(False)

    def en_btn(self):
        """ 触发事件结束， 打开全局按钮 """
        self.button_load.setEnabled(True)
        self.button_default.setEnabled(True)
        self.button_save.setEnabled(True)
        self.button_solid.setEnabled(True)

    def closeEvent(self, event:PySide6.QtGui.QCloseEvent) -> None:
        """ 重写窗口的关闭事件 """
        super().closeEvent(event)
        self.signal_operat.emit(3, 0, [None])



if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWin = E2prom_Manage()  # scaleRate)
    myWin.show()
    sys.exit(app.exec())